package com.JingYan.util.json;


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.*;
import lombok.extern.slf4j.Slf4j;

import java.util.TimeZone;

/**
 * 描述:Json转换Bean工具
 *
 * @author pengfuhui
 * @date 2022-06-02
 */
@Slf4j
public class JsonUtil {

    /**
     * 初始化ObjectMapper(统一标准)
     *
     * @return com.fasterxml.jackson.databind.ObjectMapper
     * @author pengfuhui
     * @date 2022/6/8
     */
    public static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    /**
     * bean转json
     *
     * @param bean 任意对象
     * @return java.lang.String
     * @author pengfuhui
     * @date 2022/6/8
     */
    public static String bean2json(Object bean) {
        if (bean == null) {
            return null;
        }
        String json = null;
        try {
            json = objectMapper().writeValueAsString(bean);
        } catch (Exception e) {
            log.info("bean to json is error!", e);
        }
        return json;
    }

    /**
     * json转bean
     *
     * @param json      对象json字符串
     * @param beanClass 对象类型
     * @return T 对象
     * @author pengfuhui
     * @date 2022/6/8
     */
    public static <T> T json2bean(String json, Class<T> beanClass) {
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        T t = null;
        try {
            ObjectMapper objectMapper = objectMapper();
            t = objectMapper.readValue(json, beanClass);
        } catch (Exception e) {
            log.info("json to bean is error!", e);
        }
        return t;
    }


}
